/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:DELL
 * Date:2024-11-18
 * Time:23:52
 */
public class BinarySearchTree {
    static class TreeNode{
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }
    public TreeNode root=null;
    //判断要搜索的数在哪
    public boolean search(int val){
        TreeNode cur=root;
        while (cur!=null){
            if(cur.val<val){
                cur=cur.right;
            }else if (cur.val>val){
                cur=cur.left;
            }else {
                return true;
            }
        }
        return false;
    }
    //插入：
    public boolean insert(int val){
        TreeNode node=new TreeNode(val);//要插入的节点
        //为空时
        if(root==null){
            root=node;
            return true;
        }
        //不为空时
        TreeNode cur=root;
        TreeNode parent=null;
        while (cur!=null){
            if(cur.val>val){
                parent=cur;
                cur=cur.left;
            } else if (cur.val<val) {
                parent=cur;
                cur=cur.right;
            }else {
                return false;//相等时不能插入
            }
        }
        //此时cur为空，判断王父亲的哪边插入
        if(parent.val<val){
            parent.right=node;
        }else {
            parent.left=node;
        }
        return true;
    }
    //删除
    public void remove(int val){
        TreeNode cur=root;
        TreeNode parent=null;
        while (cur!=null){
            if(cur.val>val){
                parent=cur;
                cur=cur.left;
            }else if (cur.val<val){
                parent=cur;
                cur=cur.right;
            }else {
                //删除的逻辑
                removeNode(parent,cur);
                return;
            }
        }
    }

    private void removeNode(TreeNode parent, TreeNode cur) {
        //cur的左边为空
        if(cur.left==null){
            if(cur==root){
                root=cur.right;
            }else if (cur==parent.left){
                parent.left=cur.right;
            }else {
                parent.right=cur.right;
            }
        }else if(cur.right==null){//cur右边为空
            if(cur==root){
                root=cur.left;
            }else if (cur==parent.left){
                parent.left=cur.left;
            }else {
                parent.right=cur.left;
            }
        }else {//都不为空---找cur右子树的最左边
            TreeNode targetParent=cur;
            TreeNode target=cur.right;
            while (target.left!=null){
                targetParent=target;
                target=target.left;
            }
            cur.val=target.val;
            if(target==targetParent.left){
                targetParent.left=target.right;
            }else {
                targetParent.right=target.right;
            }

        }

    }

}
